package com.xiaoyg.algorithm;

import java.util.Stack;

public class DecodeString {

    public static void main(String[] args) {
        String s = "2[abc]3[cd]ef";

        String resultStr = decodeString(s);
        System.out.println(resultStr);
    }

    private static String decodeString(String s) {
        int idx = 0;
        //累计字符
        String res = "";
        //数据栈存储数据
        Stack<Integer> countStack = new Stack<>();
        //字符串存储结果
        Stack<String> resStack = new Stack<>();
        //循环条件
        while (idx < s.length()){
            char current = s.charAt(idx);
            //如果是数字压入数字栈
            if (Character.isDigit(current)){
                StringBuffer ret = new StringBuffer();
                while (Character.isDigit(s.charAt(idx))){
                    ret.append(s.charAt(idx++));
                }
                countStack.push(Integer.parseInt(ret.toString()));
            //左边括号字符，将前面累计的字符串压栈，累计字符串置空
            }else if (current=='['){
                resStack.push(res);
                res = "";
                idx++;
            //右边括号，数字出栈累计字符
            }else if (current == ']'){
                StringBuffer temp = new StringBuffer(resStack.pop());
                int count = countStack.pop();
                for (int i = 0;i< count;i++){
                    temp.append(res);
                }
                res = temp.toString();
                idx++;
                //普通字符累计
            }else {
                res+= s.charAt(idx++);
            }
        }
        return res;
    }
}
